package com.bdqn.dao;

import com.bdqn.entity.Dept;
import com.bdqn.entity.Emp;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 模拟mybatis的实现到
 * 这里就不在用接口和实现分离
 */

@Component
public class EmpDao {

    public static List<Emp> list = new ArrayList<Emp>();
    public static List<Dept> depts = new ArrayList<Dept>();

    static {
        list.addAll(Arrays.asList(
                new Emp(1, "悟空1", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null)),
                new Emp(2, "悟空2", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null)),
                new Emp(3, "悟空3", "齐天大圣", 66666D, new Date(), new Dept(3, "研发部", null)),
                new Emp(4, "悟空4", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null)),
                new Emp(5, "悟空5", "齐天大圣", 66666D, new Date(), new Dept(2, "销售部", null)),
                new Emp(6, "悟空6", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null)),
                new Emp(7, "悟空7", "齐天大圣", 66666D, new Date(), new Dept(4, "后勤部", null)),
                new Emp(8, "悟空8", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null)),
                new Emp(9, "悟空9", "齐天大圣", 66666D, new Date(), new Dept(3, "研发部", null)),
                new Emp(10, "悟空10", "齐天大圣", 66666D, new Date(), new Dept(1, "开发部", null))
        ));

        depts.addAll(Arrays.asList(
                new Dept(1, "开发部", null),
                new Dept(2, "销售部", null),
                new Dept(3, "研发部", null),
                new Dept(4, "后勤部", null)
        ));
    }

    public static List<Emp> selectAllList() {
        return list;
    }


    public static boolean addEmp(Emp emp) {
        emp.setId(list.size() + 1);
        emp.setDept(selectDeptById(emp.getDeptId()));
        list.add(emp);
        return true;
    }


    public static List<Dept> selectAllDept() {
        return depts;
    }


    public static Dept selectDeptById(Integer id) {
        for (Dept d : depts) {
            if (d.getId() == id) {
                return d;
            }
        }
        return null;
    }


    public static Emp selectEmpById(Integer id) {
        for (Emp e : list) {
            if (e.getId() == id) {
                return e;
            }
        }
        return null;
    }

    public static boolean updateDeptById(Emp emp) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == emp.getId()) {
                list.remove(i);
                emp.setDept(selectDeptById(emp.getDeptId()));
                list.add(i, emp);
                return true;
            }

        }
        return false;
    }


    public static boolean deleteDeptById(Integer id) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == id) {
                list.remove(i);
                return true;
            }

        }
        return false;
    }
}
